from KeHu.models import KeHu,KeHu_zhaungtai,KeHugenjinlog
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView
from django.db.models import Q
from django.utils.decorators import method_decorator
from ChanPin.models import Dingdan


@method_decorator(login_required, name='dispatch')
class bjgl_kehulist(ListView):
    model = KeHu
    template_name = "bjgl_kehu_list.html"
    context_object_name = 'kehu_list'
    paginate_by = 10
    ordering = ['addtime']  # 按照id降序排列

    def get_queryset(self):
        # 获取当前登录的用户
        current_user = self.request.user
        if current_user.is_superuser:
            return KeHu.objects.filter(kehu_zhaungtai__guanzhu=2).all()
        else:
            return KeHu.objects.filter(admin_user=current_user).filter(kehu_zhaungtai__guanzhu=2)# 过滤出当前用户的数据
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        kehu_with_last_genjin = []
        for kehu in context['kehu_list']:
            # 获取当前客户的最后跟进记录
            last_genjinlog = KeHugenjinlog.objects.filter(kehu=kehu).order_by('genjintime').first()
            # 查询当前客户是否有订单 exists()方法会返回一个布尔值 count()反馈统计数量
            order_count = Dingdan.objects.filter(kehu=kehu).count()
            # 将查询结果转换为1或0，并赋值给ifhasdds
            ifhasdds = order_count
            # 如果存在跟进记录，则获取最后跟进时间，否则设置为None
            last_genjin_time = last_genjinlog.genjintime if last_genjinlog else f"暂无跟进几记录"
            # 将客户和最后跟进时间作为一个元组添加到新列表中
            kehu_with_last_genjin.append((kehu, last_genjin_time, ifhasdds))
        # 将新列表添加到上下文中，替换原始的客户列表
        context['kehu_list_with_last_genjin'] = kehu_with_last_genjin
        # 分页
        page = context['page_obj']
        context['has_previous'] = page.has_previous()
        context['has_next'] = page.has_next()
        context['previous_page_number'] = page.previous_page_number() if page.has_previous() else None
        context['next_page_number'] = page.next_page_number() if page.has_next() else None
        print(context['kehu_list'])
        return context
